package com.zoe.wan.android.example.activity.login

import android.content.Context
import android.content.Intent
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.zoe.wan.android.example.databinding.ActivityLoginBinding
import com.zoe.wan.base.BaseActivity
import com.zoe.wan.android.example.R
import com.zoe.wan.android.example.BR
import com.zoe.wan.android.example.Constants
import com.zoe.wan.android.example.activity.tab.TabActivity

class LoginActivity : BaseActivity<ActivityLoginBinding, LoginViewModel>() {

    companion object {
        const val Intent_Type_Value = 0    //0登录 1注册
        const val Intent_Type_Name = "Intent_Type_Name"
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_login
    }

    override fun getViewModelId(): Int {
        return BR.loginVm
    }

    override fun initViewData() {
        val type = intent.getIntExtra(Intent_Type_Name, -1)
        if (type == Intent_Type_Value) {
            binding?.inputPasswordTwice?.visibility = View.GONE
            binding?.registerButton?.visibility = View.VISIBLE
            binding?.loginOrRegisterBtn?.text = "确认登录"
        } else {
            binding?.inputPasswordTwice?.visibility = View.VISIBLE
            binding?.registerButton?.visibility = View.GONE
            binding?.loginOrRegisterBtn?.text = "确认注册"
        }
        binding?.loginOrRegisterBtn?.setOnClickListener {
            if (type == Intent_Type_Value) {
                login()
            } else {
                register()
            }
        }
        binding?.registerButton?.setOnClickListener {
            startIntent(LoginActivity::class.java, false)
        }
    }

    private fun login() {
        //val sp = getSharedPreferences("wanAndroidSP",Context.MODE_PRIVATE)
        viewModel?.login { username ->
            //sp.edit().putString(Constants.SP_USER_NAME,username).commit()
            SPUtils.getInstance().put(Constants.SP_USER_NAME, username)
            //LogUtils.d("SP 值为 ${sp.getString(Constants.SP_USER_NAME,"")}")
            ToastUtils.showShort("登录成功")
            startIntent(TabActivity::class.java, false)
        }
    }

    private fun register() {
        viewModel?.register {
            ToastUtils.showShort("注册成功，请登录")
            startIntent(LoginActivity::class.java, true)
        }
    }

    private fun startIntent(cls: Class<*>, hasIntent: Boolean) {
        finish()
        val intent = Intent(this, cls)
        if (hasIntent) {
            intent.putExtra(Intent_Type_Name, Intent_Type_Value)
        }
        startActivity(intent)
    }

}